//
//  SEGMonthCardCheckViewController.m
//  ExcellentHome
//
//  Created by liangxinqiang on 16/1/7.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGMonthCardCheckViewController.h"
#import "SEGMonthCardPayViewController.h"
#import "SEGMonthCardRecordViewController.h"
#import "MonthCardRequestModel.h"

@interface SEGMonthCardCheckViewController ()

@property (nonatomic, strong) SEGMonthCardPayViewController* payViewCtl;
@property (nonatomic, assign) BOOL isRequestCarNumbers;
@property (nonatomic, assign) BOOL isRequestCarInfo;

@end

@implementation SEGMonthCardCheckViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = self.title.length>0?self.title:@"月卡缴费";
    [self showCustomNavigationBackButton];

    NSString* aTitle = @"缴费记录";
    CGSize size = STRING_SIZE_FONT(1000, aTitle, 13);
    UIButton* historyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    historyBtn.frame = CGRectMake(0, 0, size.width, 20);
    [historyBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [historyBtn setTitle:@"缴费记录" forState:UIControlStateNormal];
    [historyBtn addTarget:self action:@selector(onNavigationRightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [historyBtn setTitleColor:kColor_T forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:historyBtn];
    
    [self setupUI];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    self.payViewCtl = nil;
}

- (void)setupUI {
    UIScrollView *mainScroll = [[UIScrollView alloc] init];
    mainScroll.showsVerticalScrollIndicator = NO;
    mainScroll.contentSize = CGSizeMake(LYScreenWidth(), LYScreenHeight());
    mainScroll.delegate = self;
    [self.view addSubview:mainScroll];
    [mainScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(0);
    }];
    
    
    UIImage* monthCardImage = [UIImage imageWithContentsOfFile:SEGPicName(@"monthCard")];
    UIImageView* cardView = [[UIImageView alloc] initWithFrame:CGRectMake((LYScreenWidth() - monthCardImage.size.width) / 2, 50, monthCardImage.size.width, monthCardImage.size.height)];
    [cardView setImage:monthCardImage];
    [mainScroll addSubview:cardView];
    
    UIView* aView = [[UIView alloc] initWithFrame:CGRectMake(0, 115 + monthCardImage.size.height, LYScreenWidth(), 44)];
    aView.backgroundColor = kColor_W;
    [mainScroll addSubview:aView];
    
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 50, 44)];
    label.text = @"车牌号";
    label.textColor = kColor_1;
    label.font = [UIFont systemFontOfSize:FONT_BRIEF_SIZE];
    [aView addSubview:label];
    
    carNumber = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, 200, 44)];
    carNumber.textColor = kColor_1;
    carNumber.font = [UIFont systemFontOfSize:FONT_BRIEF_SIZE];
    carNumber.delegate = self;
    carNumber.placeholder = @"请输入车牌号";
    carNumber.returnKeyType = UIReturnKeyDone;
    [aView addSubview:carNumber];
    
    UIImageView* arrow = [[UIImageView alloc] init];
    arrow.image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_more_gray")];
    arrow.frame = CGRectMake(self.view.bounds.size.width - arrow.image.size.width - 20, 14, arrow.image.size.width, arrow.image.size.height);
    [aView addSubview:arrow];
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [aView addGestureRecognizer:tap];
    
    UIButton* check = [[UIButton alloc] initWithFrame:CGRectMake(20, 179 + monthCardImage.size.height, LYScreenWidth() - 40, 44)];
    [check setTitle:@"查询" forState:UIControlStateNormal];
    [check setBackgroundImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn")] forState:UIControlStateNormal];
    [check setBackgroundImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_pre")] forState:UIControlStateHighlighted];
    [check addTarget:self action:@selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
    [mainScroll addSubview:check];
}

- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    SEGMonthCardRecordViewController* recordViewCtl = [[SEGMonthCardRecordViewController alloc] init];
    [self.navigationController pushViewController:recordViewCtl animated:YES];
}
- (void)tapAction:(UITapGestureRecognizer*)tap
{
    //防止点击多次后 请求多次 跳转多次
    if (self.isRequestCarNumbers) {
        return;
    }
    self.isRequestCarNumbers = YES;
    [[MonthCardRequestModel sharedRequestModel] requestCarNumbersWithCommunityId:kAccountCommunityID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        self.isRequestCarNumbers = NO;

        NSDictionary* dict = result;
        
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        } else {
            SEGCustomSecletViewController* customSelectView = [[SEGCustomSecletViewController alloc] init];
            customSelectView.dataArray = [NSArray arrayWithArray:[dict objectForKey:@"data"]];
            customSelectView.textKey = @"plateNo";
            customSelectView.titleName = @"选择车牌";
            customSelectView.selectDelegate = self;
            [self.navigationController pushViewController:customSelectView animated:YES];
        }
    }];
}
- (void)checkAction:(UIButton*)sender
{
    if (carNumber.text.length > 0) {
        NSDictionary* params2 = [[NSDictionary alloc] initWithObjectsAndKeys:kAccountCommunityID, @"communityId", carNumber.text, @"carNo", @"", @"communityParkingSeq", nil];
        [SVProgressHUD show];
        [[MonthCardRequestModel sharedRequestModel] requestCarInfoWithDictionary:params2 finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [SVProgressHUD dismiss];

            NSDictionary* dict = result;

            if (!isSuccessed) { //数据返回异常
                [SEGAlertView showTmepMessageWithMessage:errorMessage];
            } else {
                if (![self.navigationController.childViewControllers containsObject:self.payViewCtl]) {
                    self.payViewCtl.dataDic = [NSDictionary dictionaryWithDictionary:[dict objectForKey:@"data"]];
                    [self.navigationController pushViewController:self.payViewCtl animated:YES];
                }
            }
        }];
    }else{
        [SEGAlertView showTmepMessageWithMessage:@"请输入车牌号"];
    }
}

- (SEGMonthCardPayViewController*)payViewCtl
{
    if (_payViewCtl == nil) {
        _payViewCtl = [[SEGMonthCardPayViewController alloc] init];
        _payViewCtl.hidesBottomBarWhenPushed = YES;
    }
    return _payViewCtl;
}

#pragma mark -
#pragma mark textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField
{
    CGRect parentRect = [textField convertRect:textField.bounds toView:mainView];
    if (parentRect.origin.y > 100) {
        [mainView setContentOffset:CGPointMake(0, parentRect.origin.y - 100) animated:YES];
    }

    return YES;
}

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
    NSString* text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    [mainView setContentOffset:CGPointMake(0, 0) animated:YES];
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -
#pragma mark scrollDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [carNumber resignFirstResponder];
}

#pragma mark -
#pragma mark customselectdelegate
- (void)selectedData:(id)data
{
    NSDictionary* dic = data;
    carNumber.text = [dic objectForKey:@"plateNo"];
}

#pragma mark -
#pragma mark
- (void)onRequest_UI:(NSNotification*)notification
{
    @try {
        NSDictionary* dict = [notification userInfo];
        if ([[dict valueForKey:@"code"] isEqualToString:@"0"]) {

            SEGMonthCardPayViewController* payViewCtl = [[SEGMonthCardPayViewController alloc] init];
            payViewCtl.dataDic = [NSDictionary dictionaryWithDictionary:[dict objectForKey:@"data"]];
            payViewCtl.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:payViewCtl animated:YES];
        }
    }
    @catch (NSException* exception) {
    }
    @finally {
        //
    }
}

- (void)onRequestMonthCardList_UI:(NSNotification*)notification
{
    @try {
        NSDictionary* dict = [notification userInfo];
        if ([[dict valueForKey:@"code"] isEqualToString:@"0"]) {

            SEGCustomSecletViewController* customSelectView = [[SEGCustomSecletViewController alloc] init];
            customSelectView.dataArray = [NSArray arrayWithArray:[dict objectForKey:@"data"]];
            customSelectView.textKey = @"plateNo";
            customSelectView.titleName = @"选择车牌";
            customSelectView.selectDelegate = self;
            [self.navigationController pushViewController:customSelectView animated:YES];
        }
        else {
            [SEGAlertView showTmepMessageWithMessage:kNetworkErrorMessage];
        }
    }
    @catch (NSException* exception) {
    }
    @finally {
        //
    }
}

@end
